/*
 * SaveLoadUtils.java
 *
 * Created on 11.12.2007, 18:35:36
 *
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cz.possoft.client.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import cz.possoft.client.loader.ClassLoaderObjectInputStream;
import cz.possoft.client.saveload.SaveLoadException;
import cz.possoft.client.saveload.SaveLoadManager;
import cz.possoft.messages.PropertiesManager;
import cz.possoft.serializable.generic.Game;


/**
 * Trida slouzi k ukladani her a nacitani.
 *
 * @author mara
 */
public class SaveLoadUtils {

    public SaveLoadUtils() {
    }

    // slouzi k ulozeni hry do souboru do adresare games
    // vraci 0 - uspesne ulozeni hry
    //       1 - exception in saving game.
    //       2 - jmeno jiz existuje
    public static int writeGame(Game game, String gameName, String userName) {
            // podtrzitka v nazvu hrace i souboru nahradim pomlckama
            gameName = gameName.replace('_', '-');
            userName = userName.replace('_', '-');
            String fileName = "games/" + gameName + "_" + userName + ".svg";
            if (!controlFileName(fileName)) {
                return 2;
            }
            try {
            	SaveLoadManager.getInstance().getSaveLoadExecutor().saveGame(game, fileName);
            	return 0;
            }
            catch (SaveLoadException sle) {
            	sle.printStackTrace();
            	return 1;
            }
    }

    // vraci seznam nazvu souboru z adresare games
    public static String[] getSavedGames() {
        File gameAdr = new File("games");
        try {
            String[] p = gameAdr.list();
            return p;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // smaze vybranou hru. Vstupni pole obsahuje cely HTML kod z listu, takze je jeste treba ho zpracovat
    // vraci true pokud smazani probehlo uspesne.
    public static boolean deleteSavedGame(String gameForDelete) {
        try {
            gameForDelete = transformToFileName(gameForDelete);
            File f = new File(gameForDelete);
            return f.delete();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    // z vybraneho nazvu hry z listu vybere soubor s hrou a z nej vraci tuto hru
    public static Game loadGame(String selected) throws SaveLoadException {
        String fileName = transformToFileName(selected);
        return SaveLoadManager.getInstance().getSaveLoadExecutor().loadGame(fileName);
    }

    // z jmena souboru z listu obsahujici HTML a neobsahujici priponu vyparsuje jmeno oponenta
    public static String getUserNameFromListValue(String nameFromList) {
        int i1 = nameFromList.indexOf("red>");
        int i2 = nameFromList.indexOf("</FONT>");
        if ((i1 != -1) && (i2 != -1)) {
            String fullName = nameFromList.substring(i1 + 4, i2);
            int i3 = fullName.indexOf("_");
            if (i3 != -1) {
                return fullName.substring(i3 + 1);
            }
        }
        return "";
    }

    // z jmena souboru z listu obsahujici HTML a neobsahujici priponu vyparsuje jmeno souboru
    // a prida prefix i priponu games/
    private static String transformToFileName(String nameFromList) {
        int i1 = nameFromList.indexOf("red>");
        int i2 = nameFromList.indexOf("</FONT>");
        if ((i1 != -1) && (i2 != -1)) {
            return "games/" + nameFromList.substring(i1 + 4, i2) + ".svg";
        } else {
            return "";
        }
    }

    // zjisti jestli jmeno souboru neni obsazeno v jiz ulozenych hrach. Pokud ano, vraci false.
    private static boolean controlFileName(String fileName) {
        String[] p = getSavedGames();
        for (int i=0; i<p.length ; i++) {
            String s = p[i];
            if (fileName.equals("games/" + s)) {
                return false;
            }
        }
        return true;
    }

    // ze souboru server.txt vyparsuje jmeno hosta, ke kteremu se bude klient pripojovat
    public static String returnHostName() {
        try {
        	String s  = PropertiesManager.getInstance().getConfProperty("conf.server");
        	if (s == null) {
        		System.err.println("WARNING: Property \"conf.server\" can't be loaded from configuration. Using \"localhost\" as server host.");
        		s = "localhost";
        	}
        	return s;
        } 
        catch (Exception ex) {
        	System.err.println("WARNING: Property \"conf.server\" can't be loaded from configuration. Using \"localhost\" as server host.");
            ex.printStackTrace();
            return "localhost";
        }
    }
}
